<template>
  <div>
    <el-row :gutter="20" style="height: 100%">
      <el-col :span="5" style="height: 100%">
        <el-card style="height: 100%">

          <el-button-group circle style="margin-bottom: 5px">
            <el-button type="primary"  icon="el-icon-plus" style="padding:8px" @click="openGroupAdd" ></el-button>
            <el-button type="primary"  icon="el-icon-edit" style="padding:8px" @click="openGroupEdit" ></el-button>
            <el-button type="primary"  icon="el-icon-delete" style="padding:8px" @click="treeDelete" ></el-button>
          </el-button-group>
          <el-input style="margin-bottom: 5px" placeholder="输入关键字进行过滤"  v-model="filterText"></el-input>
          <el-tree
            class="filter-tree tree-scroll"
            v-loading="treeLoading"
            :data="groupTreeData"
            :props="defaultProps"
            node-key="nodeId"
            default-expand-all
            @node-click="handleNodeClick"
            highlight-current
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            ref="groupTree">
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="19" style="padding-left: 0">
        <el-card>
          <el-form inline :model="equipment">
            <el-form-item label="编码:" class="mgb-0" >
              <el-input v-model="equipment.fnumber"></el-input>
            </el-form-item>
            <el-form-item label="名称:" class="mgb-0">
              <el-input v-model="equipment.fname"></el-input>
            </el-form-item>
            <el-form-item class="mgb-0">
              <el-button type="primary" icon="el-icon-search" @click="searchData"></el-button>
              <el-button type="success" icon="el-icon-refresh" @click="clearData"></el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card style="margin-top: 10px">
          <div style="margin-bottom: 10px">
            <el-button type="primary" @click="openAdd">新增</el-button>
            <el-button type="primary" @click="batchEnable(0)" >批量启用</el-button>
            <el-button type="danger" @click="batchEnable(1)">批量禁用</el-button>
            <el-button type="danger" @click="batchEnable(2)">删除</el-button>
          </div>
          <el-table :data="pages.rows" v-loading="tableLoading" ref = "iTable1" @row-click="handleRowClick">
            <el-table-column align="center" type="selection" width="55"></el-table-column>
            <el-table-column label="编码" prop="fnumber" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="名称" prop="fname" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="规格" prop="fmodel" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="车间" prop="ffactoryid" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.ffactoryid ==1351115274072104961 " type="success">注塑小件车间</el-tag>
                <el-tag v-if="scope.row.ffactoryid ==1351115360973889537 " type="success">注塑大件车间</el-tag>
                <el-tag v-if="scope.row.ffactoryid ==1351452781234094082 " type="success">模压车间</el-tag>
                <el-tag v-if="scope.row.ffactoryid ==1351452856471519234 " type="success">发泡车间</el-tag>
                <el-tag v-if="scope.row.ffactoryid ==1351452932455530498 " type="success">装配车间</el-tag>
                <el-tag v-if="scope.row.ffactoryid ==1412722069223952385 " type="success">原丝车间</el-tag>
                <el-tag v-if="scope.row.ffactoryid ==1412722676445925377 " type="success">碳丝车间</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="主设备" prop="fismain" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fismain ===0 " type="success">否</el-tag>
                <el-tag v-if="scope.row.fismain ===1 " type="success">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="关键设备" prop="fiskey" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fiskey ===0 " type="success">否</el-tag>
                <el-tag v-if="scope.row.fiskey ===1 " type="success">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="fstatus">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fstatus ==='启用' " type="success">启用</el-tag>
                <el-tag v-if="scope.row.fstatus ==='禁用' " type="danger">禁用</el-tag>
                <el-tag v-if="scope.row.fstatus ==='删除' " type="danger">删除</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="openDetail(scope.row.fid)">详情</el-button>
                <el-button type="text" v-if="scope.row.fstatus === '禁用'" @click="openEdit(scope.row.fid)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="float:right; margin: 10px 0;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pages.page"
            :page-sizes="[10, 15, 20, 50]"
            :page-size="pages.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            :total="pages.totalRows">
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>
    <detail_equipment v-if="showPage.detail"  :fid="fid" :detail="treeOne" @close="addClose($event)"></detail_equipment>
    <equipment_addEdit v-if="showPage.addEdit" :fid="fid" :addOne="treeOne" :fgroupid="getfgroupid()" :status="status" @close="addClose($event)"></equipment_addEdit>
    <add_tree v-if="showPage.treeAdd" :groupAdd="groupOne" @close="addClose($event)" ></add_tree>
    <update_tree v-if="showPage.treeUpdate"  :updateOne="treeOne" @close="addClose($event)" ></update_tree>
  </div>
</template>

<script>
import Psy from "@/api/psyManage/Psy";
import Group from "@/api/psyManage/Group";
import {flatTurnTree} from '@/utils/DataTypeConvert';
import StorageHandler from '@/utils/StorageHandler';
import add_tree from "@/views/psyManage/components/add_tree";
import update_tree from "@/views/psyManage/components/update_tree";
import detail_equipment from "@/views/psyManage/components/detail_equipment";
import TieUtil from "@/utils/TieUtil";
import equipment_addEdit from "@/views/psyManage/components/equipment_addEdit";
import group from "@/views/psyManage/group";
export default {
  name: 'psy',
  components:{
    equipment_addEdit,
    add_tree,
    update_tree,
    detail_equipment
  },
  data(){
    return{
      filterText:'',
      treeLoading:'',
      groupTreeData:[],
      defaultProps:{
        children: 'children',
        label: 'nodeName'
      },
      equipment:{
        fid:0,
        fname:'',
        fnumber:'',
        fparentid:0,
        fgroupid: 0,
        fmodel:'',
        fmnemoniccode:''
      },
      nodeId:'',
      tableLoading:'',
      pages: {
        rows: [],
        page: 1, //当前页面
        pageSize: 10, // 当前页数
        totalRows: 0, // 总条数
      },
     showPage:{
       detail:false,
       update:false,
       treeAdd:false,
       treeUpdate:false,
       addEdit:false,
     },
      groupOne: {},
      stationCom: {},
      treeOne:null,
      addOne:{}
    }
  },
  watch: {
    filterText(val) {
      this.$refs.groupTree.filter(val);
    }
  },
   created(){
     this.initGroup();
     this.initGroupTree();

  },
  methods:{
    //初始化分组数
    initGroupTree() {
      this.treeLoading = true;
      const api = new Group();
      api.queryGroupTree().then(res => {
        this.treeLoading = false;
        this.groupTreeData = flatTurnTree(res.data, 'nodeId', 'nodePid', -2);
        console.log(this.groupTreeData);
      })
    },

    //点击列选中
    handleRowClick(row,column,event){
      this.$refs.iTable1.toggleRowSelection(row)
    },
    //树搜索
     filterNode(value, data) {
      if (!value) return true;
      return data.nodeName.indexOf(value) !== -1;
    },
    //点击树节点
    handleNodeClick(row, column, event){
      console.log(row)
      this.treeOne=row
      if(row.nodeId===-1){
        this.fgroupid=0
      }
       this.fgroupid=row.nodeId;
      this.page=1
       this.initGroup();
    },

    //获取表格数据源
    initGroup(){
      const api=new Psy();
      console.log(this._getData())
      this.tableLoading = true
      api.queryListPage(this._getData()).then(res =>{
        this.tableLoading=false;
        this.pages=res.data
        console.log(res.data)
      }).catch(e =>this.tableLoading=false)
    },
    _getData() {
      const data = this.equipment;
      data.page = this.pages.page;
      data.pageSize = this.pages.pageSize;
      data.fgroupid = this.fgroupid;
      return data;
    },
    // 当前页码修改时
    handleCurrentChange(page){
      this.page = page
      this.initGroup();
    },
    // 当前页数修改时
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.initGroup();
    },
    searchData(){
      this.page = 1
      this.initGroup();
    },
    clearData(){
      this.equipment.fname = '';
      this.equipment.fnumber = '';
      this.initGroup();
    },
    //打开新增弹窗
    openAdd(){
      if(this.treeOne===null){
        TieUtil.showError("提示", "请选择分类")
        return false;
      }
      this.fid=null
      this.status = 'add'
      this.showPage.addEdit = true
    },
    //打开编辑弹窗
    openEdit(fid){
      this.fid = fid
      this.status = 'update'
      this.showPage.addEdit = true
    },
    //获取单列数据用于组件传输
    getStation() {
      const stationCom = this.stationCom;
      return stationCom;
    },
    //打开详情弹窗
    openDetail(fid){
      //const api=new Psy();
      this.loading=true;
      this.fid=fid;
     /* api.detail(id).then(res=>{
        this.loading=false;
        this.stationCom=res.data;
        console.log(this.stationCom);
      }).catch(e=>this.loading=false)*/
      this.showPage.detail= true;
    },

    //新增树
    openGroupAdd() {
      if(!this.fgroupid){
        TieUtil.showError("提示", "请选择要添加的分组")
        return
      }
      const api=new Group();
      api.selectOne({pid:this.treeOne.nodeId}).then(res=>{
        this.groupOne=res.data
        if(this.treeOne.nodeId==-1){
          this.treeOne.nodeName='设备分组'
        }
        this.groupOne.nodeId=this.treeOne.nodeId;
        this.groupOne.nodePid=this.treeOne.nodePid;
      })

      this.showPage.treeAdd = true;

    },

    //修改树
    openGroupEdit() {
      if(this.treeOne===null){
        TieUtil.showError("提示", "请选择要修改的分组")
        return
      }
      this.showPage.treeUpdate = true;
    },
    //关闭新增编辑弹窗
    closeAddEdit () {
      this.showPage.addEdit= false
      this.fid = ''
      this.getData()
    },
    notRefresh(){
      this.showPage.addEdit = false
      this.fid = ''
    },
    //关闭弹框，用于组件传输
    addClose(obj) {
      console.log(obj)
      if (obj.name === 'detail') {
        this.showPage.detail = false;
      }
      if (obj.name === 'treeAdd') {
        this.showPage.treeAdd = false
      }
      if (obj.name === 'treeUpdate') {
        this.showPage.treeUpdate = false
      }
       if(obj.name === 'addEdit'){
         this.showPage.addEdit=false
       }
      if (obj.isRefresh) {
        this.initGroup();
      }
      if (obj.isRefreshTree) {
        this.initGroupTree();
      }

    },
    //加载提示
    _loading() {
      return this.$loading({
        lock: true,
        text: '请耐心等待.....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    //获取当前分组id，用户组件传输【添加】
    getfgroupid() {
      const addOne=this.treeOne;
      this.addOne.fgroupid=this.fgroupid;
      return this.addOne.fgroupid;
    },
    //组装树
    _assemblyTree(list, id, name, parentName) {
      console.log(parentName)
      let temp = {}
      let ans = []
      temp = {nodeId: -1, nodeName: parentName};
      temp.children = [];
      for (let i in list) {
        temp.children.push({
          nodeId: list[i][id],
          nodeName: list[i][name]
        });
      }
      ans.push(temp);
      return ans
    },

     //删除树节点
    treeDelete(fgroupid) {
      if (this.treeOne===null) {
        TieUtil.showError("提示", "请选择要删除的分组")
        return false;
      }
      else {
        this.$confirm('此操作将永久删除该节点, 是否继续?', '提示', {
          confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
        }).then(() => {
          const api = new Group();
          console.log(this.treeOne.nodeId)
          api.delete( {fid:this.treeOne.nodeId}).then(res => {
            this.treeLoading=true
            if (res.code === 200) {
              TieUtil.showSuccess("提示", "删除成功")
              this.initGroupTree();
            }
          }).catch(e=>this.treeLoading=false)

        })
      }
    },

    //删除分组
    deleteGroup(){
      if(this.nodeId===null){
        this.$message.error('请选择要删除的分类!')
        return false;
      }
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: `删除中，请耐心等待.....`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const http=new Group();
        http.delete( this.nodeId).then(res => {
          this.$tie.showSuccess(res.message)
          loading.close()
          this.getData()
          this.initGroupTree();
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {
        this.$tie.showInfo('已取消操作！')
      })
    },
    getSelectIdByTable () {
      var batchChoose = this.$refs.iTable1.selection;
      var fids = [];
      for (var i = 0; i < batchChoose.length; i++) {
        fids[i] = batchChoose[i].fid;
      }
      return fids;
    },
    //批量启用
    batchEnable(status){
      var fids = this.getSelectIdByTable();
      if(fids.length===0){
        this.$tie.showError('请至少选择一条数据！')
        return false;
      }
      console.log(fids)
      let http = new Psy();
      const loading = this._loading();
      http.batchEdit({ "fid": fids, "fstatus": status }).then(res => {
        this.$tie.showSuccess(res.message)
        loading.close()
        this.initGroup();
        this.getData()
      }).catch(e => {
        loading.close()
      })
    },

  },

}
</script>

<style scoped>

</style>

